package com.education.mywebviewtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);//支持js
        webView.addJavascriptInterface(new MyJs(), "xxxxxx");//设置坚挺js中方法的对象
        webView.setWebChromeClient(new WebChromeClient());
        webView.onKeyDown(WebView.KEEP_SCREEN_ON, null);
        webView.loadUrl("file:///android_asset/index.html");
        btn = (Button) findViewById(R.id.button_alert);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webView.loadUrl("javascript:myAlert()");
            }
        });
    }

    class MyJs {
        //4.4以后必须添加这个注解，不然事件无响应
        @JavascriptInterface
        public void ccccc(String content) {
            Toast.makeText(getApplicationContext(), "调用到android的方法" + content, Toast.LENGTH_SHORT).show();
            btn.setText("dianji");
        }
    }
}
